/*
 * Copyright (c) 2023-2025 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.mybatis.ext.mybatis.extension;

import com.baomidou.mybatisplus.core.conditions.SharedString;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.support.ColumnCache;
import com.baomidou.mybatisplus.core.toolkit.support.LambdaMeta;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.fasterxml.jackson.databind.util.ClassUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.apache.ibatis.reflection.property.PropertyNamer;
import org.elsfs.cloud.common.mybatis.ext.sql.CompositeSqlFragment;
import org.elsfs.cloud.common.mybatis.ext.sql.JoinType;
import org.elsfs.cloud.common.mybatis.ext.sql.TableAliasManager;

/**
 * LambdaJoinQueryWrapper
 *
 * @param <E> 实体
 */
public class LambdaJoinQueryWrapper<E>
    extends AbstractJoinWrapper<
        E,
        SFunction<E, ?>,
        LambdaJoinQueryWrapper<E>,
        WrapperSelectJoinBuilderImpl<E, SFunction<E, ?>, LambdaJoinQueryWrapper<E>>,
        WrapperSelectJoinBuilderImpl<E, SFunction<E, ?>, LambdaJoinQueryWrapper<E>>
            .WrapperJoinConditionBuilderImpl> {

  private Map<Class<?>, Map<String, ColumnCache>> columnMap = null;

  private boolean initColumnMap = false;

  public LambdaJoinQueryWrapper(E entity) {
    super(entity);
  }

  public LambdaJoinQueryWrapper(Class<E> entityClass) {
    super(entityClass);
  }

  public LambdaJoinQueryWrapper(Class<E> entityClass, TableAliasManager tableAliasManager) {
    super(entityClass, tableAliasManager);
  }

  protected LambdaJoinQueryWrapper(
      E entity,
      Class<E> entityClass,
      AtomicInteger paramNameSeq,
      Map<String, Object> paramNameValuePairs,
      MergeSegments mergeSegments,
      SharedString lastSql,
      SharedString sqlComment,
      SharedString sqlFirst,
      TableAliasManager tableAliasManager) {
    super(
        entity,
        entityClass,
        paramNameSeq,
        paramNameValuePairs,
        mergeSegments,
        lastSql,
        sqlComment,
        sqlFirst,
        tableAliasManager);
  }

  /** 子类返回一个自己的新对象 */
  @Override
  protected LambdaJoinQueryWrapper<E> instance() {
    return new LambdaJoinQueryWrapper<>(
        this.getEntity(),
        this.getEntityClass(),
        this.paramNameSeq,
        this.paramNameValuePairs,
        new MergeSegments(),
        SharedString.emptyString(),
        SharedString.emptyString(),
        SharedString.emptyString(),
        this.tableAliasManager);
  }

  /**
   * 指定查询字段
   *
   * @param condition 执行条件
   * @param columns 字段列表
   * @return children
   */
  @Override
  public final LambdaJoinQueryWrapper<E> select(boolean condition, List<SFunction<E, ?>> columns) {
    return doSelect(condition, new ArrayList<>(columns));
  }

  @Override
  @SafeVarargs
  public final LambdaJoinQueryWrapper<E> select(boolean condition, SFunction<E, ?>... columns) {
    return doSelect(condition, CollectionUtils.toList(columns));
  }

  @Override
  @SafeVarargs
  public final LambdaJoinQueryWrapper<E> select(SFunction<E, ?>... columns) {
    return doSelect(true, CollectionUtils.toList(columns));
  }

  @SafeVarargs
  public final <O> LambdaJoinQueryWrapper<E> selectOther(
      boolean condition, SFunction<O, ?>... columns) {
    return doSelect(condition, CollectionUtils.toList(columns));
  }

  protected LambdaJoinQueryWrapper<E> doSelect(boolean condition, List<SFunction<?, ?>> columns) {
    if (condition && CollectionUtils.isNotEmpty(columns)) {
      this.selectedFields.setStringValue(
          JoinWrapper.mergeSelectedFields(
              this.selectedFields.getStringValue(),
              columns.stream().map(function -> columnToString(function, true)).toList()));
      return typedThis;
    }
    return typedThis;
  }

  protected String columnToString(SFunction<?, ?> column, boolean onlyColumn) {
    ColumnCache cache = getColumnCache(column);
    final Class<?> aClass = LambdaUtils.extract(column).getInstantiatedClass(); // todo 待优化
    final var tableName = getTableAliasManager().generateAlias(aClass);
    return onlyColumn
        ? tableName + "." + cache.getColumn()
        : tableName + "." + cache.getColumnSelect();
  }

  @Override
  protected String columnToString(SFunction<E, ?> column) {
    return columnToString(column, true);
  }

  /**
   * 构建SQL片段
   *
   * @return SQL片段
   */
  @Override
  public String buildSqlFragment() {
    if (this.joinBuilders.isEmpty()) {
      return "";
    }
    return this.joinBuilders.stream()
        .map(CompositeSqlFragment::buildSqlFragment)
        .collect(Collectors.joining(" "));
  }

  @Override
  protected WrapperSelectJoinBuilderImpl<E, SFunction<E, ?>, LambdaJoinQueryWrapper<E>>
      getNewJoinBuilder(
          LambdaJoinQueryWrapper<E> elambdaJoinQueryWrapper, JoinType joinType, String table) {
    return new WrapperSelectJoinBuilderImpl<>(elambdaJoinQueryWrapper, joinType, table);
  }

  @Override
  protected WrapperSelectJoinBuilderImpl<E, SFunction<E, ?>, LambdaJoinQueryWrapper<E>>
      getNewJoinBuilder(
          LambdaJoinQueryWrapper<E> elambdaJoinQueryWrapper,
          JoinType joinType,
          String table,
          String tableAlias,
          boolean registerAlias) {
    return new WrapperSelectJoinBuilderImpl<>(
        elambdaJoinQueryWrapper, joinType, table, tableAlias, registerAlias);
  }

  @Override
  protected WrapperSelectJoinBuilderImpl<E, SFunction<E, ?>, LambdaJoinQueryWrapper<E>>
      getNewJoinBuilder(
          LambdaJoinQueryWrapper<E> elambdaJoinQueryWrapper,
          JoinType joinType,
          String table,
          String tableAlias) {
    return new WrapperSelectJoinBuilderImpl<>(elambdaJoinQueryWrapper, joinType, table, tableAlias);
  }

  @Override
  @SafeVarargs
  protected final String columnsToString(SFunction<E, ?>... columns) {
    return columnsToString(true, columns);
  }

  @SafeVarargs
  protected final String columnsToString(boolean onlyColumn, SFunction<E, ?>... columns) {
    return columnsToString(onlyColumn, CollectionUtils.toList(columns));
  }

  protected final String columnsToString(boolean onlyColumn, List<SFunction<E, ?>> columns) {
    return columns.stream()
        .map(i -> columnToString(i, onlyColumn))
        .collect(Collectors.joining(StringPool.COMMA));
  }

  /**
   * 获取 SerializedLambda 对应的列信息，从 lambda 表达式中推测实体类
   *
   * <p>如果获取不到列信息，那么本次条件组装将会失败
   *
   * @return 列
   * @throws com.baomidou.mybatisplus.core.exceptions.MybatisPlusException 获取不到列信息时抛出异常
   */
  protected ColumnCache getColumnCache(SFunction<?, ?> column) {
    LambdaMeta meta = LambdaUtils.extract(column);
    String fieldName = PropertyNamer.methodToProperty(meta.getImplMethodName());
    Class<?> instantiatedClass = meta.getInstantiatedClass();
    tryInitCache(instantiatedClass);
    return getColumnCache(fieldName, instantiatedClass);
  }

  private ColumnCache getColumnCache(String fieldName, Class<?> lambdaClass) {
    var cacheMap = columnMap.get(lambdaClass);
    if (cacheMap == null) {
      tryInitCache(lambdaClass);
    }
    cacheMap = columnMap.get(lambdaClass);
    Assert.notNull(
        cacheMap,
        "can not find lambda cache for this property [%s] of entity [%s]",
        fieldName,
        lambdaClass.getName());
    ColumnCache columnCache = cacheMap.get(LambdaUtils.formatKey(fieldName));
    Assert.notNull(
        columnCache,
        "can not find lambda cache for this property [%s] of entity [%s]",
        fieldName,
        lambdaClass.getName());
    return columnCache;
  }

  /**
   * 尝试初始化缓存
   *
   * @param lambdaClass lambdaClass
   */
  private void tryInitCache(Class<?> lambdaClass) {
    if (!initColumnMap) {
      final Class<E> entityClass = getEntityClass();
      if (entityClass != null) {
        lambdaClass = entityClass;
      }
      columnMap = new HashMap<>();
      final var getColumnMap = LambdaUtils.getColumnMap(lambdaClass);
      columnMap.put(lambdaClass, getColumnMap);
      Assert.notNull(
          getColumnMap, "can not find lambda cache for this entity [%s]", lambdaClass.getName());
      initColumnMap = true;
    }
    if (!ClassUtil.hasClass(getEntityClass(), lambdaClass) && lambdaClass != null) {
      if (columnMap == null) {
        columnMap = new HashMap<>();
      }
      final var getColumnMap = LambdaUtils.getColumnMap(lambdaClass);
      columnMap.put(lambdaClass, getColumnMap);
      Assert.notNull(
          getColumnMap, "can not find lambda cache for this entity [%s]", lambdaClass.getName());
    }
  }

  @Override
  public void clear() {
    super.clear();
    selectedFields.toNull();
  }
}
